#!/bin/sh
. /etc/utils.sh

SNIPROXY_CONFIG_FILE=/tmp/sniproxy.conf
SNIPROXY_PIDFILE=/tmp/run/sniproxy.pid
SNIPROXY_PORT=8443

start_iptables () {
  stop_iptables
  ip46tables -A sniproxy-input -p tcp --dport "$SNIPROXY_PORT" -j ACCEPT
  iptables -t nat -A sniproxy-nat -p tcp --dport https -j REDIRECT --to-ports "$SNIPROXY_PORT"
}

stop_iptables () {
  ip46tables -F sniproxy-input
  iptables -t nat -F sniproxy-nat
}

case "$1" in
  start)
    # If $SNIPROXY_CONFIG_FILE is missing, use the system default config.
    ln -s /etc/sniproxy.conf "$SNIPROXY_CONFIG_FILE"
    babysit 60 startpid "$SNIPROXY_PIDFILE" setuid nobody \
      sniproxy -c "$SNIPROXY_CONFIG_FILE" -f 2>&1 | logos sniproxy &
    start_iptables
    ;;
  stop)
    killpid "$SNIPROXY_PIDFILE"
    stop_iptables
    ;;
  restart)
    $0 stop; $0 start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac
